/*
 * OPIAM Suite
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package opiam.admin.applis.demo.plugins;

import opiam.admin.applis.demo.beans.Person;

import opiam.admin.faare.config.javabeans.JBTrigger;
import opiam.admin.faare.exception.ServiceException;
import opiam.admin.faare.persistence.javabeans.JBTop;
import opiam.admin.faare.service.UserContext;
import opiam.admin.faare.service.services.triggers.TriggerInterface;

import org.apache.log4j.Logger;

import java.io.FileOutputStream;
import java.io.PrintWriter;

//DW/2688/BeginPatch
import java.net.URLDecoder;
//DW/2688/EndPatch

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Properties;


/**
 * This class allows to manage the authorizations file.
 * It is called by the trigger service when a "Service manager" person modifies an entry. 
 */
public class AuthorizationTraceAction implements TriggerInterface
{
    /** Instance of the log4j logger. */
    private static Logger _logger =
        Logger.getLogger(AuthorizationTraceAction.class.getName());

    /** File name. */
    private String filename = "/authorization/authorizationfiles.txt";

    /**
     * Method called at application initialization.
     *
     * @param props parameters of the trigger, set in triggers_conf.xml
     * @param directory Configuration directory if any.
     *
     */
    @Override
	public void initialize(Properties props, String directory)
    {
    }

    /**
     * Method called to perform the trigger action.
     *
     * @param triggerDesc Trigger descriptor.
     * @param entry Entry which is subject of the operation launching the trigger.
     * @param userContext Connected user context.
     *
     * @throws ServiceException in case of error.
     */
    @Override
	public void execute(JBTrigger triggerDesc, JBTop entry,
                        UserContext userContext
                       ) throws ServiceException
    {
        try
        {
            String classPath =
                (AuthorizationTraceAction.class.getResource("AuthorizationTraceAction.class")).toString();
            int pos = classPath.indexOf("/classes/");
            String refPath = null;
        	if (classPath.indexOf("file:/") >= 0)
        	{

                int nbsub = 5;

                if (classPath.substring(7, 9).equals(":/"))
                { /* this is Windows */
                    nbsub = 6;
                }
        	    refPath = classPath.substring(nbsub, pos);
        	}

//DW/2688/BeginPatch
            refPath = URLDecoder.decode (refPath, "UTF-8");
//DW/2688/EndPatch
            
            String filepath = refPath + filename;

            _logger.debug("filepath = " + filepath);

            FileOutputStream fos = new FileOutputStream(filepath, true);
            PrintWriter pw = new PrintWriter(fos);
            StringBuffer sb = new StringBuffer();
            Date dt = new Date();
            GregorianCalendar gc = new GregorianCalendar();
            gc.setTime(dt);
            sb.append(gc.get(Calendar.YEAR));
            sb.append("/");
            sb.append(gc.get(Calendar.MONTH) + 1);
            sb.append("/");
            sb.append(gc.get(Calendar.DAY_OF_MONTH));
            sb.append(" - User ");
            sb.append(((Person) entry).getId());
            sb.append(" - Authorization : ");

            String auth = ((Person) entry).getAppAuth();

            if ((auth == null) || (auth.equals("")))
            {
                sb.append("off");
            }
            else
            {
                sb.append(auth);
            }

            pw.println(sb.toString());

            _logger.debug("Add : " + sb.toString());

            pw.close();
        }
        catch (Exception ex)
        {
            _logger.error(ex.toString());
        }
    }
}
